<?php

namespace zhtfrontend\models\datas;

use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\models\datas\Customer;
use Yii;
use common\components\extenders\MenuManage;
use yii\base\Event;
use yii\helpers\Html;

/**
 * This is the model class for table "{{%class_student}}".
 *
 * @property integer $id
 * @property integer $class_id
 * @property integer $code
 * @property integer $student_id
 * @property integer $order_id
 * @property integer $status
 * @property integer $start_time
 * @property integer $end_time
 * @property string $class_code
 * @property integer $headmaster
 * @property integer $pclass_id
 * @property integer $is_book
 * @property integer $is_old
 * @property integer $associate_id
 *
 */
class ClassManage extends \zhtfrontend\components\bases\BaseModel
{
    /**Manage
     * @inheritdoc
     */
    public $ids;
    public $classroom_id;
//    public $is_book;

    public $telephone;
    public $student_name;
    public $customer_name;
    public $password;
    public $password_r;
    public $age;
    public $card_id;
    public $sex;
    public $lesson_id;
    public $num;

    const EVENT_OPEN_MONTH = 'remindClassbeforeMonth';
    const EVENT_OPEN_WEEK = 'remindClassbeforeWeek';
    const EVENT_OPEN_DAY = 'remindClassbeforeDay';
    const EVENT_END_MONTH = 'remindClassendMonth';

    public static function tableName()
    {
        return '{{%class_manage}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'is_book'], 'required', 'except' => ['add']],
            [['is_old', 'mechanic_id', 'is_delete', 'type','lesson_id','admin_id','cycle','num'], 'integer'],
            [['headmaster', 'start_time','num'], 'required', 'when' => function ($model) {
                return !empty($model->status);
            }, 'on' => ['open', 'open_old']],
            [['start_time'], 'start_time_check_old', 'on' => ['open_old']],
            [['start_time'], 'start_time_check', 'on' => ['open','addlesson']],
            [['start_time'], 'art_start_time_check', 'on' => ['art_open']],
            [['headmaster', 'status'], 'integer', 'on' => ['open', 'open_old']],
            [['headmaster', 'code', 'status', 'end_time', 'pclass_id'], 'integer', 'except' => ['add', 'open', 'open_old']],

            ['telephone', 'match', 'pattern' => '/^1([0-9]{9})/', 'message' => '手机号码格式错误', 'on' => ['add']],
            [['telephone'], 'string', 'max' => 11, 'min' => 11, 'on' => ['add']],
            [['password'], 'string', 'max' => 60, 'min' => 6, 'on' => ['add']],
            [['student_name', 'password', 'telephone', 'customer_name', 'card_id', 'password_r', 'age', 'sex'], 'required', 'on' => ['add']],
            [['card_id'], 'card_check', 'on' => ['add']],
            [['password_r'], 'card_password_r', 'on' => ['add']],
            [['num','start_time'],'required','on'=>['addlesson']],
            [['start_time'],'check_start','on'=>['addlesson']],
//            ['student_id', 'match', 'pattern' => '/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/ ', 'message' => '身份证格式错误','on'=>['add']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'class_id' => Yii::t('zhtfrontend', 'ID'),
            'class_code' => Yii::t('zhtfrontend', '班级编号'),
            'headmaster' => Yii::t('zhtfrontend', '班主任编号'),
            'code' => Yii::t('zhtfrontend', '排课id'),
            'status' => Yii::t('zhtfrontend', '开班状态'),
            'start_time' => Yii::t('zhtfrontend', '开始时间'),
            'end_time' => Yii::t('zhtfrontend', '结束时间'),
            'pclass_id' => Yii::t('zhtfrontend', '升级老班编号'),
            'ids' => Yii::t('zhtfrontend', '绑定学生'),
            'is_book' => Yii::t('zhtfrontend', '开班类型'),
            'associate_id' => Yii::t('zhtfrontend', '关联id（若is_old=1 关联排课表id 若is_old=0 关联商品表id)）'),
            'telephone' => Yii::t('zhtfrontend', '手机号'),
            'student_name' => Yii::t('zhtfrontend', '学生姓名'),
            'customer_name' => Yii::t('zhtfrontend', '会员名'),
            'password' => Yii::t('zhtfrontend', '密码'),
            'password_r' => Yii::t('zhtfrontend', '确认密码'),
            'age' => Yii::t('zhtfrontend', '学生出生年份'),
            'sex' => Yii::t('zhtfrontend', '学生性别'),
            'card_id' => Yii::t('zhtfrontend', '卡号'),
            'mechanic_id' => Yii::t('zhtfrontend', '机构id'),
            'is_old' => Yii::t('zhtfrontend', '是否老班'),
            'is_delete' => Yii::t('zhtfrontend', '是否删除（0 否 1 是）'),
            'type' => Yii::t('zhtfrontend', '班级类型'),
            'child_id' => Yii::t('zhtfrontend', '艺教学班级id'),
            'classroom_id' => Yii::t('zhtfrontend', '教室'),
            'lesson_id' => Yii::t('zhtfrontend', '课次'),
            'admin_id' => Yii::t('zhtfrontend', '管理员id'),
            'cycle' => Yii::t('zhtfrontend', '上课周期'),
            'num' => Yii::t('zhtfrontend', '课次数'),
        ];
    }

    public function extraFields()
    {
        return [
            'course_name' => function () {
                return isset($this->classmanageattribute->course) ? $this->classmanageattribute->course : '';
            },
            'classroom_name' => function () {
                 if(isset($this->classmanageattribute->room_type) && $this->classmanageattribute->room_type == 1){
                     $room_name = '';
                     if(!empty($this->classmanageattribute->classroom_name)){
                         $room_name = '-'.$this->classmanageattribute->classroom_name;
                     }
                     return isset($this->classmanageattribute->room_group_name)?$this->classmanageattribute->room_group_name.$room_name:'';
                 }else{
                     return isset($this->classmanageattribute->classroom_name) ? $this->classmanageattribute->classroom_name : '';
                 }

            },
            'teacher_name' => function () {
                $teacherArr = ClassManageTeacher::find()->select('teacher_name')->where(['class_id'=>$this->class_id])->column();
                $str = '';
                if(!empty($teacherArr)){
                    $str = implode(',',$teacherArr);
                }
                return $str;
            },
            'mechanic_name' => function () {
                return isset($this->mechanic->name) ? $this->mechanic->name : '';
            },
            'opening_number' => function () {
                return isset($this->classmanageattribute->opening_number) ? $this->classmanageattribute->opening_number : 0;
            },
            'max_number' => function () {
                return isset($this->classmanageattribute->max_number) ? $this->classmanageattribute->max_number : 0;
            },
            'student_count' => function () {
                return isset($this->classStudent) ? count($this->classStudent) : 0;
            },

            'status_name' => function () {
                switch ($this->status) {
                    case 0:
                        return Yii::t('zhtfrontend', '未开班');
                    case 1:
                        return Yii::t('zhtfrontend', '已开班');
                    case 2:
                        return Yii::t('zhtfrontend', '已结束');
                }
            },
            'class_time' => function () {
                $str = '';
                if($this->classmanagetime){
                    foreach ($this->classmanagetime as $val){
                        $str .= Util::getWeek($val->class_day).$val->start_time.'-'.$val->end_time;
                    }
                }
                return $str;
            },
            'start_day'=>function(){
                if(!empty($this->start_time)){
                    return \Yii::$app->formatter->asDate($this->start_time);
                }else{
                    return \Yii::t('zhtfrontend','未开班');
                }
            },
            'end_day'=>function(){
                if(!empty($this->end_time)){
                    return \Yii::$app->formatter->asDate($this->end_time);
                }else{
                    return \Yii::t('zhtfrontend','未开班');
                }
            },

            'arttitle' => function (){
                 return isset($this->artteaching->title)?$this->artteaching->title:'';
            },
            'arttime' => function (){
                 if(!empty($this->artteaching)){
                     return Util::getWeek($this->artteaching->class_day).' '. $this->artteaching->star_time.'-'.$this->artteaching->end_time;
                 }
                 return '';
            },
            'arttitle_type' => function (){
                if(isset($this->artteaching->type)){
                    switch ($this->artteaching->type){
                        case 1:
                            return \Yii::t('zhtfrontend','益智');
                        case 2:
                            return \Yii::t('zhtfrontend','音乐');
                        default :
                            return \Yii::t('zhtfrontend','形体');
                    }
                }
                 return isset($this->artteaching->title)?$this->artteaching->title:'';
            },
//            'is_goods'=>function(){
//                $result = ClassManageGoods::find()->where(['class_id'=>$this->class_id])->orderBy('created_at DESC')->one();
//                if($result == null){
//                    return \Yii::t('zhtfrontend', "<button type='button' style='color:#ff659a; background-color:#fff;border:0' title='点击生成商品' class='shelve' data-id='".$this->class_id."'>生成商品</button>");
//                }else{
//                    //if($this->type == 1){
//                        if($result->created_at != $this->classmanageattribute->updated_at){
//                            return \Yii::t('zhtfrontend', "<button type='button' style='color:#0E4DAA; background-color:#fff;border:0' title='点击更新商品' class='shelve' data-id='".$this->class_id."'>更新商品</button>");
//                        }else{
//                            return \Yii::t('zhtfrontend','最新商品');
//                        }
//                   // }
//
//                }
//            },

            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'open' => function ($data) {
                            if ($data['status'] == 1) {
                                return '<span style="color:#ccc">开课</span>';
                            } else {
                                $max_end_time = ClassManage::find()->where(['code' => $data['code'], 'status' => 1])->max('end_time');
                                if ($max_end_time != null && $max_end_time > time())
                                    return '<span style="color:#ccc">开课</span>';
                                else
                                    return '';
                            }
                        },
                        'details' => function ($data) {
                            if ($data['status'] == 0) {
                                return '<span style="color:#ccc">学员列表</span>';
                            } else {
                                return '';
                            }
                        },
                        'lesson' => function ($data) {
                            if ($data['status'] == 0) {
                                return '<span style="color:#ccc">课时详情</span>';
                            } else {
                                return '';
                            }
                        }

                    ]
                )->create();
            },
            'newoperate' => function(){

                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'open' => function ($data) {
                            if ($data['status'] != 0) {
                                return '<button class="yx-btn-disabled" type="button">开班</button>';
                            } else {
                                return '';
                            }
                        },
                        'delete'=> function (){
                            return '';
                        },
                        'details'=>function(){
                            return '';
                        },
                        'addlesson' => function($data){
                            if ($data['status'] != 1) {
                                return '<button class="yx-btn-disabled" type="button">增加课次</button>';
                            } else {
                                return '';
                            }
                        },
                        'close' =>function($data){
                            $lessonIds = ClassLesson::find()->select('lesson_id')->where(['class_id'=>$data['class_id']])->column();
                            $check = StudentCheck::find()->where(['class_lesson_id'=>$lessonIds,'status'=>0])->all();
                            if ($data['status'] == 0 || $check !=null) {
                                return '<button class="yx-btn-disabled" type="button">关闭班级</button>';
                            } else {
                                return '';
                            }
                        }

                    ]
                )->create();
            },
            'artoperate' => function(){

                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'open' => function ($data) {
                            if ($data['status'] == 1) {
                                return '<button class="yx-btn-disabled" type="button">开班</button>';
                            } else {
                                return '';
                            }
                        },
                        'delete'=> function (){
                            return '';
                        },
                        'details'=>function(){
                            return '';
                        },
                        'lesson'=>function($data){
                            if ($data['status'] == 0) {
                                return '<button class="yx-btn-disabled" type="button">课时详情</button>';
                            } else {
                                return '';
                            }
                        }
                    ]
                )->create();
            }
        ];
    }

//    public function getArrangeCourse()
//    {
//        return $this->hasOne(ArrangeCourse::className(), ['id' => 'code']);
//    }
    public function card_check($attribute)
    {
        if ($attribute != null) {
            $data = Customer::find()->where(['card_id' => $this->$attribute])->andWhere(['<>', 'mobile', $this->telephone])->andWhere(['site_id' => Fun::getSiteId()])->one();
            if ($data != null || strlen($this->$attribute) != 10 || !is_numeric($this->$attribute)) {
                $this->addError($attribute, Yii::t('zhtfrontend', '卡号错误'));
            }
        }
    }

    public function card_password_r($attribute)
    {
        if ($this->$attribute != $this->password) {
            $this->addError($attribute, Yii::t('zhtfrontend', '两次密码不一致，请重新输入'));
        }
    }

    //对应arrangement表
    public function getArrangeMent()
    {
        return $this->hasOne(Arrangement::className(), ['id' => 'associate_id']);
    }

    //对应goods表
    public function getGoods()
    {
        return $this->hasOne(Goods::className(), ['id' => 'associate_id']);
    }

    //对应teacher表
    public function getTeacher()
    {
        return $this->hasOne(Teacher::className(), ['id' => 'teacher_id']);
    }

    //对应classroom表
    public function getClassroom()
    {
        return $this->hasOne(Classroom::className(), ['id' => 'classroom_id']);
    }

    public function getClassStudent()
    {
        return $this->hasMany(ClassStudent::className(), ['class_manage_id' => 'class_id']);
    }

    public function getMechanic()
    {
        return $this->hasOne(Mechanic::className(), ['id' => 'mechanic_id']);
    }

    public function getClassmanageattribute(){
        return $this->hasOne(ClassManageAttribute::className(),['class_id'=>'class_id']);
    }

    public function getClassmanagetime(){
        return $this->hasMany(ClassManageTime::className(),['class_id'=>'class_id']);
    }

    public function getArtteaching(){
        return $this->hasOne(ArtTeaching::className(),['id'=>'associate_id']);
    }

    public function start_time_check_old($attribute)
    {
        if (!empty($this->status)) {
            $date = (int)date("N", \Yii::$app->formatter->asTimestamp($this->start_time));
            $time = \Yii::$app->formatter->asTimestamp($this->start_time);
            $nowtime = strtotime(date('Y-m-d'));
            $class_day = isset($this->arrangeMent->classroom_attr_id) ? $this->arrangeMent->classroom_attr_id : '';
            if ($time < $nowtime) {
                $this->addError($attribute, Yii::t('zhtfrontend', '开课时间不能小于当前时间'));
            }
            if ($class_day == '') {
                $this->addError($attribute, Yii::t('zhtfrontend', '排课表中无对应信息'));
            }
            $classroom_attr_ids = explode(',', $class_day);
            $weeks = ClassroomAttr::find()->select('classday')->where(['id' => $classroom_attr_ids])->column();
            if (!in_array($date, $weeks)) {
                $this->addError($attribute, Yii::t('zhtfrontend', '时间所在星期必须与上课星期相同'));
            }
        }
    }

    public function start_time_check($attribute)
    {
        if (!empty($this->status)) {
            $date = (int)date("N", \Yii::$app->formatter->asTimestamp($this->start_time));
            $classDays = ClassManageTime::find()->select('class_day')->where(['class_id' => $this->class_id])->column();
            if (!in_array($date, $classDays)) {
                $this->addError($attribute, Yii::t('zhtfrontend', '时间所在星期必须与上课星期相同'));
            }
        }
    }

    public function art_start_time_check($attribute)
    {
        if (!empty($this->status)) {
            $date = (int)date("N", \Yii::$app->formatter->asTimestamp($this->start_time));
            $time = \Yii::$app->formatter->asTimestamp($this->start_time);
            $class_day = ArtTeaching::find()->select('class_day')->where(['id' => $this->associate_id])->column();
            if ($time < strtotime(date('Y-m-d'))) {
                $this->addError($attribute, Yii::t('zhtfrontend', '开课时间不能小于当前时间1'));
            }
            if ($date != $class_day[0]) {
                $this->addError($attribute, Yii::t('zhtfrontend', '时间所在星期必须与上课星期相同'));
            }
        }
    }

    public function check_start($attribute){
        $maxLesson = ClassLesson::find()->where(['class_id'=>$this->class_id])->orderBy('lesson DESC')->limit(1)->one();
        $maxdate = strtotime(date('Y-m-d',$maxLesson->class_date));
        if(strtotime($this->$attribute) <= $maxdate){
            $this->addError($attribute, Yii::t('zhtfrontend', '时间要大于最后一节课时间'));
        }
    }

    public function afterFinda($type='week')
    {
        switch ($type){
            case 'month':
                $this->trigger(ClassManage::EVENT_OPEN_MONTH);
                break;
            case 'week':
                $this->trigger(ClassManage::EVENT_OPEN_WEEK);
                break;
            case 'day':
                $this->trigger(ClassManage::EVENT_OPEN_DAY);
                break;
            case 'endmonth':
                $this->trigger(ClassManage::EVENT_END_MONTH);
                break;
            default:break;
        }
    }

//    public function afterDelete(){
//        ClassManageTime::deleteAll(['class_id'=>$this->class_id]);
//        ClassManageAttribute::deleteAll(['class_id'=>$this->class_id]);
//    }
}
